<template>

    <UxDialog class="saving-dialog" :visible="option" :can-close="false" :hide="child ? 'hidden' : ''">

        <!-- 错误 -->
        <div class="failure" v-if="status == 'failure'">
            <h6 @click="onFailure()"><svg-icon name="dialog-close-medium" /></h6>
            <figure>
                <img src="@/assets/images/designer/dialog-save-failure.png" alt="" />
                <strong>Save failed! </strong>
                <span>Failed to save your design, please check your internet connection and try again</span>
            </figure>
            <button @click="doLoop(value)" type="primary">Save again</button>
        </div>

        <!-- 上传中 -->
        <div class="saving-loading" v-if="status == 'saving'">
            <UxLoading2 :loading="true" />
        </div>

        <!-- 上传完成选择框 -->
        <div class="complete" v-if="status == 'success'">
            <h6 @click="close()" v-if="isBlank"><svg-icon name="dialog-close-medium" /></h6>

            <div class="complete-preview">
                <UxTemplateInputInline v-model="complete.template_name" @change="updateName($event)"
                                       @blur="updateName($event)" @focus="nameCache = complete.template_name" />
                <CommonTemplatePreview :pieces.sync='complete.design_list'
                                       :baseModel="completeModesFilter[previewIndex]"
                                       :baseColor="getColorPreview(complete)" size="large" />

                <ul>
                    <li v-for="(model, index) in completeModesFilter" :key="model.id"
                        :class="{ active: previewIndex == index }" @click="previewIndex = index">
                        <CommonTemplatePreview :baseModel="model" :baseColor="getColorPreview(complete)" size="large" />
                    </li>
                </ul>

                <button @click="setNextTo('edit')" v-if="!isBlank">Edit</button>
            </div>

            <div class="complete-link">
                <figure><svg-icon name="checkbox-active" /></figure>
                <p>
                    <span>Your</span>
                    <a @click="setNextTo('template')">Product template</a>
                    <span>has been saved.</span>
                </p>

                <cite>
                    <button type="secondary" @click="setNextTo('order')">
                        <svg-icon name="design-save-order" />
                        <span>Create an order</span>
                    </button>
                    <button type="secondary" @click="setNextTo('store')">
                        <svg-icon name="design-save-store" />
                        <span>Add to store</span>
                    </button>
                </cite>

                <div class="complete-link-new" @click="setNextTo('design')" v-if="!isBlank">Create a new template with
                    the same product</div>
                <div class="complete-link-blank" v-else>
                    We do not charge for the first design added to the product template. If you give up the freebie and
                    make an order with a blank template, you will enjoy a 5% discount upon checkout.
                </div>
            </div>

        </div>

        <!-- 下单购买 -->
        <UserMakeOrder v-model="order" :beforeClose="beforeClose" v-show="child == 'order'" />

        <!-- 同步到商店 -->
        <UserSyncStore v-model="store" :beforeClose="beforeClose" v-show="child == 'store'" />
    </UxDialog>
</template>
<script>
import DesignUtils from "@/utils/DesignUtils.js";
import { getStitchesByBase64 } from "@/utils/EmbroideryDst.js";


export default {
    name: "DrawingDialog",
    // props: ["value"],
    data () {
        return {
            value: null,
            status: 'saving', // saving|failure|success
            option: null,
            complete: null, // 保存完成

            previewIndex: 0,
            nameCache: '',
            nameLoading: false,
            child: '',
            order: null, // 生成订单
            store: null, // 同步到商店

        };
    },
    computed: {
        isBlank () {
            return this.option && this.option.is_blank;
        },

        completeModesFilter () {
            const complete = this.complete || {}
            const tag = complete.model_tag || 'hanging';
            const models = complete.model_img || [];

            const tag_able = ['hanging', 'flat lay', 'model'].filter(i => models.find(model => model.model_tag == i))
            const tag_active = tag_able.indexOf(tag) >= 0 ? tag : tag_able[0];
            return models.filter(m => m.model_tag == tag_active)
        }
    },

    methods: {

        // 开始保存
        doSaving (value, cb) {
            // 半自定图层
            // 使用领标
            // 缓存
            this.previewIndex = 0;
            this.value = value;
            this.callback = cb
            this.doLoop(this.value);
        },

        doLoop (value) {
            // 格式化数据
            this.option = this.formatOption(value)
            this.status = 'saving'

            // setTimeout(() => {
            //     // // ----------------

            //     this.status = 'failure'
            //     // this.onSuccess({
            //     //     id: 1,
            //     //     template_name: 'template 123',
            //     //     design_list: [],
            //     //     model_tag: '',
            //     //     model_img: [],
            //     // })

            // }, 1000);



            // 生成图片
            this.getOutputImage(this.option).then(option => {
                // 保存数据
                this.status = 'saving'
                return this.saveDesignData(this.option)

            }).then(response => {
                // 保存下一步
                if (response && response.code == 0 && response.data) {
                    this.onSuccess(response.data);
                } else {
                    return Promise.reject(response.msg)
                }
            }).catch(error => {
                // 异常
                this.status = 'failure'
            })

        },

        beforeClose () {
            if (this.status == 'success' && this.child) {
                this.child = ''
                return false;
            }
        },


        // 模式化数据
        formatOption (value) {

            const option = value || {}
            const result = {
                spu: option.spu || '', // 商品spu
                product_id: option.product_id || '', // 产品id
                template_id: option.template_id || '', // 模板id，如果是二次编辑，这个值才会有
                brand_label_id: option.brand_label_id || '', // 如果有选中了领标
                color_id: option.color_id || "", // 选中的颜色
                model_tag: option.model_tag,
                is_blank: true,
                pieces: [], // 设计面信息
                models: Array.isArray(option.models) ? JSON.parse(JSON.stringify(option.models)) : [], // 模特信息
            }

            const platens_opt = value.platens || []

            const pieces = Array.isArray(option.pieces) ? JSON.parse(JSON.stringify(option.pieces)) : [];

            // layers格式化、计算半自定义图层
            pieces.map((piece) => {
                const layers = Array.isArray(piece.layers) ? piece.layers : JSON.parse(piece.layers || '[]');
                piece.layers = layers;

                // 没有设计面的，表示空白模板
                if (result.is_blank && layers.length > 0) {
                    result.is_blank = false;
                }

                if (piece.type == 2) {
                    // 刺绣版带
                    const platens = piece.layers.map(layer => {

                        const dists = layer.dists || []
                        const count = dists.reduce((p, c) => p + c.stitches_count || 0, 0)
                        const platens_active = platens_opt.find(i => i.code == layer.platens_id)
                        const colors = []

                        dists.map(dst => {
                            if (dst.type == 'text') {
                                const stitches = getStitchesByBase64(dst.stitches)
                                const color = stitches.filter(i => i[2] == 5).length + 1;
                                const slice = dst.line_color.split(',').slice(0, color)
                                colors.push(...slice)
                            } else {
                                colors.push(...dst.line_color.split(','))
                            }
                        })


                        return {
                            platens_id: layer.platens_id || '',
                            name: layer.name || '',
                            width: layer.w,
                            height: layer.h,
                            left: layer.x,
                            top: layer.y,
                            rotate: layer.rotate,
                            scale: layer.scale || 1,
                            product_dist: '',
                            product_preview: '',
                            product_colors: colors.join(','),
                            stitches_count: count,
                            price: DesignUtils.getEmbPrice(count, platens_active),
                            dists: dists
                        }
                    })

                    piece.optional_platens = JSON.stringify(piece.optional_platens)
                    piece.platens = platens
                    piece.price = platens.reduce((p, c) => p + c.price || 0, 0)
                    piece.layers = []

                    result.pieces.push(piece)


                } else {
                    piece.optional_platens = '[]'
                    piece.platens = []

                    result.pieces.push(piece)
                }

            });

            // 没有版带的不添加
            result.pieces.map(piece => {
                if (piece.type == 2) {
                    piece.platens = piece.platens.filter(i => i.dists.length > 0)
                }
            })

            // 如果有brand_label_id，则领标数据清空
            return result
        },

        // 生成预览图
        getOutputImage (option) {

            const request = {
                spu: option.spu,
                models: option.models,
                pieces: option.pieces,
            };


            // this.close();
            return this.$http("Drawer.batchDraw", request).then((result) => {
                if (result.code == 0) {
                    // 临时保存的数据
                    const data = result.data || []
                    const cache = new Map(data.map((i) => [i.type + "-" + i.id, i]));
                    // 设计面
                    option.pieces.map((item) => {
                        let select = cache.get("piece-" + item.id) || {}
                        let platen_output = select.platens || []
                        let output = select.output || "";
                        // 要把缩略图的litimg去掉
                        item.output_img = output.replace(/-litimg(\.(jpe?g|png))/gi, "$1");
                        (item.platens || []).map((platen, index) => {
                            platen.product_preview = platen_output[index] || '';
                            platen.dists.map(dst => {
                                // 当是上传的版带时，这里不用保存针迹，减少流量
                                if (dst.dst_id) {
                                    // delete dst.stitches
                                }
                            })
                        })
                    });

                    // 模特
                    option.models.map((item) => {
                        let select = cache.get("model-" + item.id) || {}
                        let output = select.output || "";
                        item.model_url = output
                    });

                    return Promise.resolve(option);
                } else {
                    return Promise.reject(result.msg);
                }
            });

        },

        // 保存数据
        saveDesignData (option) {

            // 请求参数
            const price = {
                free: null,
                total: 0,
                list: [],
                process: new Map(),
            }
            const request = {
                product_id: option.product_id,
                brand_label_id: option.brand_label_id,
                show_color_num: option.color_id,
                is_blank: option.is_blank,
                model_tag: option.model_tag,
                design_json: [],
                model_img: [],
                extra_price: 0,
            };


            // 设计面信息
            request.design_json = option.pieces.map(piece => {

                const custom_count = piece.layers.filter((layer) => !!layer.customize).length;

                if ((piece.type == 1 && piece.layers.length <= 0) || (piece.type == 2 && piece.platens.length <= 0)) {
                    // 没有设计信息
                } else {
                    // 正面或背面
                    const free = /^Back Side|Front Side/.test(piece.canvas_name);
                    const max = !price.free || piece.price > price.free.price;
                    price.free = piece.type == 1 && free && max ? piece : price.free
                    price.list.push(piece)
                    price.total += piece.price;
                    price.process.set(piece.type || 1, true)
                }

                if (request.brand_label_id && piece.canvas_name == "Neck Label Inner") {
                    // 如果有brand_label_id，则领标数据清空
                    return {
                        ...piece,
                        layers: '[]',
                        platens: '[]',
                        output_img: '',
                        custom_count: custom_count,
                    }
                } else {
                    return {
                        ...piece,
                        layers: JSON.stringify(piece.layers),
                        platens: JSON.stringify(piece.platens),
                        custom_count: custom_count,
                    }
                }
            })

            // 模特信息
            request.model_img = option.models.map(model => {
                return {
                    id: model.id,
                    model_url: model.model_url || "",
                    surface_name: model.surface_name,
                    mask_opacity: model.mask_opacity,
                    mask_color: model.mask_color,
                    model_type: model.model_type || 1, // 1旧版，2新版
                    model_tag: model.model_tag || 'hanging',
                    model_name: model.model_name || 'Hanging',
                    model_color: model.model_color || '{}',
                };
            })


            // 价格
            // (dtg 免正面或背面最贵的一个面) + emb + 多工艺组合费用
            // 多工艺组合费用
            const total = price.free ? price.total - price.free.price : price.total;
            const compose = price.process.size > 1 ? 299 : 0; // 多工艺组合费用是 299
            request.extra_price = total + compose


            // return Promise.reject('')

            if (option.template_id) {
                // 重新保存
                return this.$http("storeTemplate.putTemplate/" + option.template_id, request);
            } else {
                // 新设计
                return this.$http("Designer.saveDraft", request);
            }
        },

        // 设置跳转到下一页
        setNextTo (type) {
            const template = this.complete;
            if (type == "order" && template) {
                // 下单购买
                this.clearParentDesign();
                this.child = 'order';
                // this.order = {
                //     spu: template.spu, //商品的SPU用于确认SKU
                //     title: template.title, //标题
                //     model_img: template.model_img, // 模特信息
                //     design_list: template.design_list, //设计信息
                //     source: "template", //商品来源
                //     design_id: template.id, //商品来源
                //     extra_price: template.extra_price, // 设计面价格
                //     is_blank: template.is_blank, // 是否空白模板
                //     color_base: template.show_color_num, // 默认颜色
                //     tag: template.tag_design_info, // 吊牌
                //     pack: template.pack_design_info // 包装
                // };
            } else if (type == "store") {
                // 同步到商店
                this.clearParentDesign();
                this.child = 'store';
                // this.store = { ...this.complete };
            } else if (type == "template") {
                // 跳到我的模板
                this.clearParentDesign();
                this.$router.push("/user/template");
            } else if (type == "edit") {
                // 修改
                this.$parent.template_id = (this.complete || {}).id || 0;
                this.close();

            } else if (type == "design") {
                // 重新设计
                this.$parent.template_id = 0;
                this.clearParentDesign();
                this.close();
            }
        },

        clearParentDesign () {
            try {
                this.$parent.clearDesign && this.$parent.clearDesign();
            } catch (error) {
            }
        },

        // 保存失败，且取消再次保存
        onFailure () {
            this.callback && this.callback()
            this.callback = null;
            this.close()
        },

        // 保存成功事件
        onSuccess (data) {
            this.status = 'success'
            this.complete = data;
            this.store = { ...this.complete };
            this.order = {
                spu: this.complete.spu, //商品的SPU用于确认SKU
                title: this.complete.title, //标题
                model_img: this.complete.model_img, // 模特信息
                design_list: this.complete.design_list, //设计信息
                source: "template", //商品来源
                design_id: this.complete.id, //商品来源
                extra_price: this.complete.extra_price, // 设计面价格
                is_blank: this.complete.is_blank, // 是否空白模板
                color_base: this.complete.show_color_num, // 默认颜色
                tag: this.complete.tag_design_info, // 吊牌
                pack: this.complete.pack_design_info // 包装
            };
            this.callback && this.callback(data)
            this.callback = null;
        },


        // 关闭对话框
        close () {
            this.status = '';
            this.option = null;
            this.complete = null;
            this.order = null;
            this.store = null;
            this.$emit("input", null);
        },

        getColorPreview (item) {
            const color = item.show_color_num;
            const list = item.color_list || [];
            const select = list.filter((i) => i.color_num == color || i.color_id == color);
            return select[0] || list[0];
        },

        // 编辑名字
        async updateName (event) {
            let value = (this.complete || {}).template_name;
            if (this.nameLoading) {
                // 正在加载中
            } else if (!this.complete) {
                // 正在加载中的不管
            } else if (this.nameCache == value || this.nameCache == '') {
                // 值相同的不管
            } else if (!/[\w\W]+/.test(value)) {
                this.$uxMessage.error("At least one character");
                this.complete.template_name = this.nameCache;
            } else {
                this.nameLoading = true;
                let response = await this.$http("storeTemplate.putName/" + this.complete.id, { name: value });
                if (response.code === 0) {
                    this.$uxMessage.success("Template renamed successfully");
                    this.nameLoading = false;
                } else {
                    this.$uxMessage.error("Failed to rename template");
                    this.complete.template_name = this.nameCache;
                    this.nameLoading = false;
                }
            }
        },

    },
};
</script>
<style lang="scss" scoped>
.saving-dialog {
    &[hide='hidden'] {
        &::v-deep .dialog-content {
            opacity: 0 !important;
        }
    }

    &~.make-order,
    &~.sync-store {
        translate: none !important;
        background: none !important;

        &::v-deep .dialog-close {
            width: 26px;
            height: 26px;
            top: 12px;
            left: 12px;
            background-size: 26px 26px;
            background-image: url(@/assets/images/designer/dialog-back.png);
            background-position: center center;
            background-repeat: no-repeat;

            svg {
                display: none;
            }

            &:hover {
                background-color: #ebebeb;
            }
        }

        &::v-deep .async-list {
            padding-top: 54px;
        }
    }
}

.saving-loading {
    width: 880px;
    height: 488px;
    position: relative;

    .loading {
        background: none;
    }
}

// 失败
.failure {
    width: 320px;
    height: 414px;
    box-sizing: border-box;
    padding: 14px;
    display: flex;
    flex-direction: column;
    position: relative;

    &>h6 {
        z-index: 1;
        position: absolute;
        right: 4px;
        top: 4px;
        width: 24px;
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #555;
        transition: all 0.3s;
        cursor: pointer;
        border-radius: 4px;

        svg {
            width: 10px;
            height: 10px;
        }

        &:hover {
            background-color: rgba(255, 0, 0, 0.1);
            color: #8c1c14;
        }
    }

    figure {
        margin-top: 38px;
        flex: 1;
        text-align: center;
        display: flex;
        flex-direction: column;
        align-items: center;

        img {
            vertical-align: top;
            width: 80px;
            height: 80px;
        }

        &>strong {
            margin-top: 54px;
            font-size: 16px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #000000;
            line-height: 22px;
        }

        &>span {
            margin: 18px 0 0;
            font-size: 14px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #000000;
            line-height: 22px;
        }
    }
}

.complete {
    width: 880px;
    height: 488px;
    box-sizing: border-box;
    display: flex;
    opacity: 1;
    transition: opacity 0.3s;

    &>h6 {
        z-index: 1;
        position: absolute;
        right: 4px;
        top: 4px;
        width: 24px;
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #555;
        transition: all 0.3s;
        cursor: pointer;
        border-radius: 4px;

        svg {
            width: 10px;
            height: 10px;
        }

        &:hover {
            background-color: rgba(255, 0, 0, 0.1);
            color: #8c1c14;
        }
    }
}

.complete-preview {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 50%;
    padding: 24px 0;
    position: relative;

    &::v-deep {
        .custom-icon {
            width: 32px;
            height: 32px;
        }
    }

    &::after {
        content: '';
        position: absolute;
        left: 100%;
        top: 0;
        bottom: 0;
        border-right: 1px solid #f0f0f0;
    }

    &>.input-inline::v-deep {
        max-width: 292px;
        overflow: hidden;

        .input-inline-textarea {
            overflow: hidden;

            span,
            textarea {
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                display: block;
                font-size: 14px;
                font-family: Roboto-Medium, Roboto;
                font-weight: 500;
                color: #000000;
            }
        }
    }

    &>.template-preview {
        margin-top: 6px;
        width: 292px;
        height: 292px;
        position: relative;

        &::v-deep .svg-icon {
            max-width: 150px;
            max-height: 150px;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }

        &::v-deep figure[loaded='error'] img {
            left: 20%;
            top: 20%;
            width: 60%;
            height: 60%;
        }
    }

    ul {
        display: flex;
        margin-top: 12px;

        li {
            width: 56px;
            height: 56px;
            border: 2px solid #e6e6e6;
            border-radius: 4px;
            overflow: hidden;
            margin: 0 6px;
            cursor: pointer;
            transition: all 0.2s;

            &:hover {
                border-color: #f6b2cd;
            }

            &.active {
                border-color: #f6b2cd;
            }
        }
    }

    button {
        margin-top: 10px;
        width: 132px;
        height: 32px;
    }
}

.complete-link {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 50%;
    padding: 24px 0;

    &>figure {
        width: 32px;
        height: 32px;
        border-radius: 32px;
        background-color: #59b692;
        display: flex;
        align-items: center;
        justify-content: center;

        svg {
            color: #fff;
            width: 14px;
            height: 14px;
        }
    }

    p {
        margin-top: 10px;
        font-size: 16px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #000000;
        line-height: 18px;
        text-align: center;
        display: flex;

        a {
            display: inline-block;
            padding: 0 4px;
            cursor: pointer;
            font-weight: bold;
            color: #ea4c89;
            border-bottom: 1px solid #ea4c89;

            &:hover {
                border-color: transparent;
            }
        }
    }

    cite {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 56px 0;

        button {
            width: 220px;
            height: 46px;

            svg {
                width: 22px;
                height: 22px;
                margin-right: 4px;
                font-weight: normal;
                transition: all 0.2s;
            }

            span {
                display: inline-block;
                vertical-align: top;
                line-height: 44px;
                font-size: 16px;
            }

            &+button {
                margin-top: 24px;
            }

            &:nth-child(1) svg {
                color: #51b8df;
            }

            &:nth-child(2) svg {
                color: #f6be33;
            }

            &:hover svg {
                color: #ea4c89 !important;
            }
        }
    }

    .complete-link-new {
        margin-top: 5px;
        font-size: 14px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #292929;
        line-height: 16px;
        cursor: pointer;
        border-bottom: 1px solid #292929;

        &:hover {
            color: #ea4c89;
            border-color: transparent;
        }
    }

    .complete-link-blank {
        cursor: default;
        user-select: none;
        font-size: 14px;
        font-weight: 400;
        color: #6c855a;
        text-decoration: none;
        background: #f6faf5;
        margin: 0 20px;
        padding: 12px;
        border-radius: 8px;
    }
}
</style>
